package com.ktwlsoft.archivemanage.service.utils.webSocket;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * 客户端端点
 * 通过客户端端点向其他客户端发送数据
 *
 * 调用方式:client.sendMessage(String.valueOf(relatedPersonId),otherContent);
 * 关闭链接:client.closeSocket();
 * */
@Component
@ClientEndpoint
public class WebSocketMyClient {

    private Session session;

    @Value("${server.port}")
    private String prot;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    /**用户端点*/
    private static final String USERNO = "service";

    /**服务器客户端端点默认URL*/
    private String url;

    /**
     * 连接建立成功调用的方法
     * */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.session = session;
        System.out.println("=========== webSocketClient与Socket服务器建立连接成功 ===========");
    }

    /**
     * 收到消息后调用的方法
     *
     * @param message 发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.print("webSocketClient客户端端点接收到消息--->" + message);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Throwable t) {
        System.out.println("=========== webSocketClient连接过程中发生错误 ===========");
        t.printStackTrace();
    }
    /**
     * 连接关闭调用的方法
     * @throws Exception Exception
     */
    @OnClose
    public void onClose() throws Exception{
        System.out.println("=========== webSocketClient关闭与Socket服务器的连接 ===========");
    }

    /**
     * 关闭链接方法
     * @throws IOException IOException
     */
    public void closeSocket() throws IOException{
        this.session.close();
    }

    /**
     * 发送消息
     * @param message message
     * @throws Exception Exception
     */
    private void sendMessage(String message) throws Exception{
        if(this.session == null){
            start();
        }
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送消息
     * @param userNo 接收消息的编号(不为空指定发送,为空全部发送)
     * @param message 发送消息内容
     * @throws Exception
     */
    public void sendMessage(String userNo,Object message) throws Exception{
        if(message == null || "".equals(message)){
            throw new Exception("webSocketClient参数不正确");
        }
        Map<String,Object> map = Maps.newHashMap();
        map.put("userNo",userNo != null?userNo:"0");
        map.put("message",message);
        sendMessage(JSON.toJSONString(map));
    }

    /**
     * 启动客户端并建立链接
     * */
    public void start(String url) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        this.url = url;
        try {
            this.session = container.connectToServer(WebSocketMyClient.class, URI.create(url));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动客户端并建立链接
     * */
    public void start() {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        url = "ws://localhost:"+ prot + contextPath +"/webSocket/" + USERNO;
        try {
            this.session = container.connectToServer(WebSocketMyClient.class, URI.create(url));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
